package com.koko.service.Impl;

import com.koko.constant.MessageConstant;
import com.koko.context.BaseContext;
import com.koko.exception.CartGameAlreadyExistException;
import com.koko.feign.GameFeignService;
import com.koko.game.vo.GameCartVO;
import com.koko.mapper.CartMapper;
import com.koko.order.entity.Cart;
import com.koko.order.vo.CartGameVO;
import com.koko.result.Result;
import com.koko.service.CartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private GameFeignService gameFeignService;
    @Autowired
    private CartMapper cartMapper;

    /**
     * 将游戏添加到购物车
     * @param gameId
     */
    @Override
    public void addGameToUserCart(Long gameId) {
        Cart cart = new Cart();
        cart.setGameId(gameId);
        cart.setUserId(BaseContext.getCurrentId());
        // 1. 判断购物车中是否已满
        Integer count = cartMapper.checkIfExists(cart);
        if (count > 10) {
            throw new CartGameAlreadyExistException(MessageConstant.CART_GAME_TOO_MUCH);
        }
        // 2. 购物车中没有，则插入
        cartMapper.insert(cart);
    }

    /**
     * 查询购物车中的数据
     * @return
     */
    @Override
    public List<CartGameVO> getAllGames() {
        List<Cart> cartList = cartMapper.getGamesByUserId(BaseContext.getCurrentId());
        List<CartGameVO> list = cartList.stream().map((item) -> {
            CartGameVO cartGameVO = new CartGameVO();
            // 遍历获取游戏数据
            Result<GameCartVO> result = gameFeignService.getGameOnCartByGameId(item.getGameId());
            BeanUtils.copyProperties(result.getData(), cartGameVO);
            cartGameVO.setId(item.getId());
            return cartGameVO;
        }).collect(Collectors.toList());
        return list;
    }

    /**
     * 通过id删除订单游戏表
     * @param ids
     */
    @Override
    @Transactional
    public void deleteById(List<Long> ids) {
        for (Long id : ids) {
            cartMapper.deleteById(id);
        }
    }

    /**
     * 通过userID删除购物车列表
     * @param userId
     */
    @Override
    public void deleteByUserId(Long userId) {
        cartMapper.deleteByUserId(userId);
    }
}
